import requests
import json
import zipfile
import os

# 获取当前工作目录的路径
path = os.getcwd()

# 获取书籍ID列表
def getBooksId():
    # 请求获取书籍信息的URL
    url = "http://reciteword.youdao.com/reciteword/v1/param?key=normalBooks&keyfrom=reciteword.1.5.12.android&vendor=xiaomi&mid=9&imei=CQlkYjRlZWEwYzZlYmRiYjkyCXVua25vd24%253D&screen=1080x1920&model=Mi_Note_3&version=1.5.12"
    # 解析返回的JSON数据，提取书籍列表
    bookList = json.loads(requests.get(url).text)["data"]["normalBooks"]["bookList"]
    BooksId = []
    # 遍历书籍列表，提取每本书的ID
    for book in bookList:
        BooksId.append(book["id"])
    return BooksId

# 获取书籍下载链接
def getBooksDownLink(booksId):
    # 请求获取书籍下载信息的URL
    url = "http://reciteword.youdao.com/reciteword/v1/getBooksInfo?keyfrom=reciteword.1.5.12.android&vendor=xiaomi&mid=9&imei=CQlkYjRlZWEwYzZlYmRiYjkyCXVua25vd24%253D&screen=1080x1920&model=Mi_Note_3&version=1.5.12"
    # 构建请求的负载数据
    payload = {'bookIds': json.dumps(booksId), 'reciteType': 'normal'}
    # 解析返回的JSON数据，提取书籍下载信息
    booksInfo = json.loads(requests.post(url, data = payload).text)["data"]["normalBooksInfo"]
    downlink = []
    # 遍历书籍信息，提取每本书的标题和下载链接
    for book in booksInfo:
        downlink.append({"title": book["title"], "link": book["offlinedata"]})
    return downlink

# 下载书籍并解压
def downBook(fileName, link):
    # 发送请求下载书籍
    r = requests.get(link, stream=True)
    # 提取链接中的文件名
    linkname = link[link.find(".com/") + 5:]
    # 将下载的内容写入文件
    with open(linkname, 'wb') as fd:
            fd.write(r.content)
    try:
        # 构建zip文件的完整路径
        zipfileName = path + "/" + linkname
        print(zipfileName)
        # 打开zip文件并解压到指定目录
        file = zipfile.ZipFile(zipfileName)
        file.extractall(fileName)
        file.close()
    except Exception as e:
        # 打印解压过程中出现的异常
        print(e)

# 主函数
def main():
    # 获取书籍ID列表
    BooksId = getBooksId()
    print(BooksId)
    # 获取书籍下载链接
    downlink = getBooksDownLink(BooksId)
    print(downlink)

    # 下载每本书并解压
    for book in downlink:
        downBook(book["title"], book["link"])

# 程序入口
if __name__ == '__main__':
    main()